package com.kevin.data.batch.component;

import com.kevin.data.batch.configuration.BizItemProcessor;
import com.kevin.data.batch.configuration.BizJobListener;
import com.kevin.data.batch.model.Log;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库读写处理
 */
@Component
public class DbBatchComponent {

    @Resource(name = "bizDatasource")
    private DataSource dataSource;

    @Resource
    private BizJobListener jobListener;

    @Resource
    private BizItemProcessor bizItemProcessor;

    @Resource
    private JobRepository jobRepository;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Bean("dbJob")
    public Job dbJob() throws Exception {
        return new JobBuilder("dbJob", jobRepository).start(dbStep()).listener(jobListener).build();
    }

    private Step dbStep() throws Exception {
        return new StepBuilder("dbStep", jobRepository)
                .allowStartIfComplete(true).<Log, Log>chunk(3, transactionManager)
                .reader(dbItemReader())
                .processor(bizItemProcessor)
                .writer(list -> list.forEach(data -> System.err.println("dbItemReader : " + data))).build();
    }

    private ItemReader<Log> dbItemReader() throws Exception {
        JdbcPagingItemReader<Log> reader = new JdbcPagingItemReader<>();
        // 设置数据源
        reader.setDataSource(dataSource);
        // 每次取多少条记录
        reader.setFetchSize(5);
        // 设置每页数据量
        reader.setPageSize(5);
        // 指定 SQL 查询语句 SELECT id, description, method, remote_addr, user_agent, client_Id FROM log
        MySqlPagingQueryProvider mySqlPagingQueryProvider = new MySqlPagingQueryProvider();
        // 设置查询字段
        mySqlPagingQueryProvider.setSelectClause("id,description,method,remote_addr,user_agent,client_id");
        // 设置查询表名
        mySqlPagingQueryProvider.setFromClause("FROM log");
        // 将读取到的数据转换为 Log 对象
        reader.setRowMapper((resultSet, rowNum) -> new Log()
                .setId(resultSet.getString(1))
                .setDescription(resultSet.getString(2))
                .setMethod(resultSet.getString(3))
                .setRemoteAddr(resultSet.getString(4))
                .setUserAgent(resultSet.getString(5))
                .setClientId(resultSet.getString(6)));

        Map<String, Order> sort = new HashMap<>(1);
        sort.put("id", Order.ASCENDING);
        // 设置排序,通过 ID 升序
        mySqlPagingQueryProvider.setSortKeys(sort);
        reader.setQueryProvider(mySqlPagingQueryProvider);
        // 设置 namedParameterJdbcTemplate 等属性
        reader.afterPropertiesSet();
        return reader;
    }

}
